<template>
  <div class="main-container">
    <div class="main-container-top-header"
         v-if="urlParamObj.name">
      <span>{{ urlParamObj.name }}</span>
      <span v-if="showTotal">({{ tableConfig.pagination.total }})</span>
    </div>
    <div class="pending-list-top-content">
      <div>
        <a-tabs class="a-tabs"
                @change="handleTabsChange">
          <a-tab-pane v-for="tabKey in Object.keys(tabs)"
                      :key="tabKey"
                      :tab="tabs[tabKey]">
            <div class="pending-list-main">
              <div :id="searchConditionContainerId"></div>
              <div class="pending-list-header">
                <div style="flex: 1; overflow: hidden">
                  <CommonToolbar :allToolBtns="allToolBtns"
                                 @buttonClick="buttonClick"></CommonToolbar>
                </div>
                <div class="search-part">
                  <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                                  style="width: 272px"
                                  :allowClear="true"
                                  @change="onInputSearchValueChange"
                                  @search="handleSearch" />
                  <div style="margin-left: 12px; display: flex">
                    <SearchCondition :containerParentId="searchConditionContainerId"
                                     :conditions="searchConditions"
                                     @valueChange="handleSearchConditionChange"
                                     @expandChange="expandChange">
                    </SearchCondition>
                  </div>
                </div>
              </div>
              <div class="pending-list-content"
                   style="flex: 1">
                <AVirtuallyTable ref="avirtuallyTable"
                                 style="cursor: pointer"
                                 :rowKey="tableConfig.rowKey"
                                 size="small"
                                 :pagination="true"
                                 :openVirtuallyModel="true"
                                 :paginationOption="tableConfig.pagination"
                                 :columns="tableConfig.columns"
                                 :dataSource="tableConfig.tableDataList"
                                 :titleRightMenus="tableConfig.titleRightMenus"
                                 :loading="loading"
                                 :localstorageKey="getLocalStorageKey"
                                 @paginationChange="handleTableChange"
                                 @paginationShowSizeChange="paginationShowSizeChange"
                                 @rowClick="rowClick">
                  <!-- 标题 -->
                  <span slot="subject"
                        slot-scope="{ record }">
                    <TitleTableRender :slotData="record"></TitleTableRender>
                  </span>
                  <!-- 督办期限 -->
                  <span slot="awakeDate"
                        slot-scope="{ record }">
                    <SuperviseDeadLineNameTableRender :slotData="record"></SuperviseDeadLineNameTableRender>
                  </span>
                  <!-- 分类 -->
                  <span slot="appName"
                        slot-scope="{ text, record }">
                    <a-tag @click="openUrl(record.entityType)"
                           :class="[
                        'tag-show',
                        {
                          collaborationStyle: record.entityType == 1,
                          edocStyle: record.entityType == 2,
                          signedOrsendStyle: record.entityType == 3
                        }
                      ]">
                      {{ text }}
                    </a-tag>
                  </span>
                </AVirtuallyTable>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>
<script>
  import { getParams, loadComponentsThemeDefaultCSS } from '../../utils';
  import CommonToolbar from '../../components/common-toolbar/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import TitleTableRender from './components/title-table-render.vue';
  import SuperviseDeadLineNameTableRender from './components/supervise-deadLineName-table-render.vue';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import { formatRequestDataToJSON } from '@/utils/api';

  export default {
    name: 'SuperviseColumn',
    mixins: [smartCodeMixin],
    components: {
      CommonToolbar,
      SearchCondition,
      AVirtuallyTable,
      TitleTableRender,
      SuperviseDeadLineNameTableRender
    },
    computed: {
      getLocalStorageKey() {
        return window._currentUser.id + 'SUPERVISE_COLUMN';
      }
    },
    data() {
      return {
        tabs: {
          all: '全部(0)',
          collaboration: '协同(0)',
          edoc: '公文(0)'
        },
        showTotal: true,
        currentTab: 'all',
        allToolBtns: [],
        entityType: [1, 2],
        tableConfig: {
          rowKey: 'id',
          pagination: {
            page: 1,
            // pageSize: 20,
            total: 0
            // pageSizeOptions: ['10', '20', '30', '40', '50'],
            // showTotal: (total) => `${this.$i18n('orgrole.total_items', total)}`,
            // showSizeChanger: true
          },
          rowSelection: {
            columnWidth: 60,
            selectedRowKeys: [],
            onChange: this.handleSelectChange
          },
          tableDataList: [],
          columns: [],
          titleRightMenus: {
            asc: true,
            desc: true,
            freeze: true,
            fieldset: true
          },
          selectedRows: []
        },
        searchConditionContainerId: 'search-condition-container-parent',
        searchConditions: [],
        queryCondition: {},
        urlParamObj: {},
        searchValue: '',
        cachParams: {},
        loading: false
      };
    },
    created() {
      this.urlParamObj = getParams(window.location.search);
      this.urlParamObj.name
        ? (this.urlParamObj.name = window.decodeURIComponent(this.urlParamObj.name))
        : '';
      // 非Vue响应数据
      this.searchText = '';
      this.searchConditionsValue = {};
      this.toolCheckboxListValue = {};
      this.init();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    methods: {
      init() {
        // this.initTableData();
        this.initMetaData();
      },
      initTableData(parasObj) {
        this.loading = true;
        const importLevel = this.queryCondition.importLevel
          ? [this.queryCondition.importLevel.join(',')]
          : [];
        let cachParams = {
          entityType: this.entityType,
          subject: [this.searchValue],
          templete: parasObj
            ? parasObj.conditionType == 'templete'
              ? [parasObj.conditionValue]
              : []
            : [],
          importLevel: importLevel,
          sender: this.queryCondition.sender ? [this.queryCondition.sender] : [],
          createDate: this.queryCondition.createDate
            ? [this.queryCondition.createDate.startDate, this.queryCondition.createDate.endDate]
            : []
        };
        this.cachParams = cachParams;
        const pageInfo = {
          page: this.tableConfig.pagination.page
        };
        if (this.tableConfig.pagination.pageSize) {
          pageInfo.size = this.tableConfig.pagination.pageSize;
        }
        const sendParams = [pageInfo, cachParams];
        const args = `managerMethod=getSuperviseList4Portal&arguments=${formatRequestDataToJSON(
          sendParams
        )}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=superviseManager&rnd=6714`;

        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();

        window.axios
          .post(url, args, {
            cancelToken: this.cancelToken.token,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((data, err) => {
            console.log(err, 'err');
            const result = data.data;
            if (result) {
              this.tableConfig.tableDataList = result.data;
              this.tableConfig.pagination.total = result.total;
              this.loading = false;
            }
          });
      },
      initMetaData() {
        const headerParams = {
          key: 'SUPERVISE_SECTION',
          platform: 0,
          arguments: {
            fragmentId: this.urlParamObj.fragmentId || '',
            bigTitleIndex: this.urlParamObj.bigTitleIndex || '',
            ordinal: this.urlParamObj.ordinal || '',
            entityType: this.entityType
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, headerParams).then((data, err) => {
          const recieveData = data.data.data;
          const globalParam = recieveData ? recieveData.globalParam : undefined;
          this.supportSmartCode = globalParam ? globalParam.supportSmartCode : undefined;
          this.initTableData(recieveData.globalParam);
          this.initToolButtons();
          const tabItems = recieveData.pageHead.items;
          for (let tab = 0; tab < tabItems.length; tab++) {
            let tabType = tabItems[tab].key;
            let total = tabItems[tab].value;
            let title = tabItems[tab].title;
            this.tabs[tabType] = `${title}(${total})`;
          }
          if (!window._hasPlugin('collaboration') || !recieveData.globalParam?.showCol) {
            //不需要展示协同
            delete this.tabs['collaboration'];
          }
          if (!window._hasPlugin('edoc') || !recieveData.globalParam?.showEdoc) {
            //不需要展示公文
            delete this.tabs['edoc'];
          }
          this.searchConditions = recieveData.searchConditions.filter(
            (item) => item.key !== 'subject'
          );
          this.tableConfig.columns = [];
          recieveData.tableColumns.forEach((item) => {
            if (item.type != 'CHECKBOX' && item.key !== 'id') {
              this.tableConfig.columns.push({
                title: item.title,
                width: item.width,
                dataIndex: item.key,
                ellipsis: true,
                key: item.key,
                fixed: false,
                dropdownMenus: {
                  asc: true,
                  desc: true,
                  freeze: true,
                  fieldset: true
                },
                scopedSlots: { customRender: item.key == 'title' ? 'subject' : item.key },
                customCell: () => {
                  return {
                    style: {
                      padding: '0 8px',
                      height: '38px',
                      cursor: 'pointer'
                    }
                  };
                }
              });
            }
          });
        });
      },
      initToolButtons() {
        this.allToolBtns = []
        if (this.isHaveSmartCodePermission()) {
          this.allToolBtns.push(this.smartCodeBtnInfo);
        }
      },
      handleTabsChange(tabType) {
        this.currentTab = tabType;
        switch (this.currentTab) {
          case 'edoc':
            this.entityType = [2];
            break;
          case 'collaboration':
            this.entityType = [1];
            break;
          default:
            this.entityType = [1, 2];
        }
        this.init();
      },
      handleSearchConditionChange(condition) {
        this.queryCondition = condition;
        this.initTableData();
      },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
        this.queryCondition.subject = this.searchValue;
      },
      handleSearch(val) {
        this.queryCondition.subject = val;
        this.searchValue = val;
        this.tableConfig.pagination.page = 1;
        this.initTableData();
      },
      handleTableChange(page, pageSize) {
        this.tableConfig.pagination.page = page;
        this.tableConfig.pagination.pageSize = pageSize;
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.tableConfig.pagination.page = 1;
        this.tableConfig.pagination.pageSize = size;
        this.initTableData();
      },
      rowClick(record) {
        this.linkToSummary(
          record.affairId,
          window.escapeStringToHTML(window.escapeStringToHTML(record.title)),
          record.summaryId,
          record.status,
          record.entityType
        );
      },
      linkToSummary(affairId, subject, summaryId, status, entityType) {
        var url =
          window._ctxPath +
          '/collaboration/collaboration.do?method=summary&openFrom=supervise&type=0&affairId=' +
          affairId +
          '&showTab=true';
        if (entityType == 2) {
          url =
            window._ctxPath +
            '/edocController.do?method=detailIFrame&summaryId=' +
            summaryId +
            '&openFrom=supervise&affairId=' +
            affairId +
            '&type=' +
            status;
        } else if (entityType == 3) {
          url =
            window._ctxPath +
            '/govdoc/govdoc.do?method=summary&summaryId=' +
            summaryId +
            '&openFrom=supervise&affairId=' +
            affairId +
            '&type=' +
            status;
        }
        this.showSummayDialogByURL(url);
      },
      showSummayDialogByURL(url) {
        try {
          //公文、协同都是affairId，会议是Id
          var affairIdIndex = url.indexOf('affairId');
          var idIndex = url.indexOf('id');
          var id = '';
          if (affairIdIndex != -1) {
            id = window.getMultyWindowId('affairId', url);
            this.openWindow({ url: url, id: id });
          } else if (idIndex != -1) {
            id = window.getMultyWindowId('id', url);
            this.openWindow({ url: url, id: id });
          } else {
            this.openWindow({ url: url });
          }
        } catch (e) {
          console.log(e);
        }
      },
      openWindow(obj) {
        var url = obj.url;
        var a8Top = window.getA8Top();
        if (a8Top.isMultipleTabs && url.indexOf('showTab=true') != -1 && !this.isOcipSummary(obj)) {
          a8Top.openCtpWindow(obj);
        } else {
          window.openCtpWindow(obj);
        }
      },
      //ocip推送过来的数据，不走多页签
      isOcipSummary(obj) {
        if (window._hasPlugin('ocip')) {
          let url = obj.url;
          if (url.indexOf('method=summary&') != -1 && url.indexOf('showTab=true') != -1) {
            let params = url.split('&');

            for (let i = 0; i < params.length; i++) {
              if (params[i].indexOf('affairId=') == -1) {
                continue;
              }
              let affairIds = params[i].split('=');
              if (affairIds[0] == 'affairId' && affairIds[1]) {
                return window.callBackendMethod(
                  'ocipColManager',
                  'checkIsExchangeAffair',
                  affairIds[1]
                );
              }
            }
          }
        }
        return false;
      },
      openUrl(app) {
        if (app == '2' || app == '3') {
          app = 4;
        }
        if (app == '1') {
          window.location.href =
            window._ctxPath +
            '/supervise/supervise.do?method=superviseFrame&managerType=mySupervise&quotaType=all' +
            window.CsrfGuard.getUrlSurffix();
        } else {
          window.location.href =
            window._ctxPath +
            '/supervise/supervise.do?method=listSupervise&app=' +
            app +
            window.CsrfGuard.getUrlSurffix();
        }
      },
      buttonClick() {
        this.showSmartCode && this.showSmartCode();
      },
      // 智码扫码成功后，智码预处理时，获取解码参数
      getSmartCodeDecodeParam() {
        var obj = this.getSearchValueObj();
        obj.openFrom = 'moreSupervise';
        return obj;
      },
      getSearchValueObj() {
        var o = new Object();
        o.entityType = this.entityType;
        o.importLevel = this.cachParams.importLevel;
        o.category = '';
        o.templete = '';
        o.sender = this.cachParams.sender;
        o.createDate = this.cachParams.createDate;
        return o;
      },
      searchConditon(obj) {
        var condtionType = $('#condtionType').val();
        var condtionValue = $('#condtionValue').val();
        if ('importLevel' == condtionType) {
          obj.importLevel = [condtionValue];
        }
        if ('category' == condtionType) {
          obj.category = [condtionValue];
        }
        if ('templete' == condtionType) {
          obj.templete = [condtionValue];
        }
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      expandChange(isExpanded) {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable[0].resizeTable();
        });
        console.log(isExpanded);
      }
    }
  };
</script>
<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss" scoped>
  .main-container {
    height: 100%;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .main-container-top-header {
      padding: 12px 16px 0 20px;
      font-size: 16px;
      font-weight: 600;
      color: #333333;
    }
    .pending-list-top-content {
      position: relative;
      flex: 1 1 auto;

      > div {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
      }
    }
  }

  .a-tabs {
    height: 100%;
    display: flex;
    flex-direction: column;
    &::v-deep .ant-tabs-bar {
      margin: 0 0 0px 20px;
    }
    &::v-deep .ant-tabs-content {
      flex-grow: 1;
    }
    &::v-deep .ant-tabs-top-content.ant-tabs-content-animated{
      transition: none !important
    }
    .pending-list-main {
      position: relative;
      height: 100%;
      display: flex;
      flex-direction: column;

      .pending-list-header {
        display: flex;
        padding: 12px 10px 12px 20px;
        height: 54px;
        box-sizing: border-box;
      }

      .search-part {
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;
      }

      .pending-list-content {
        flex: 1;
        padding: 0 10px 0 20px;
      }

      .tag-show {
        border-radius: 2px;
        border: none;
        cursor: pointer;
      }
      .collaborationStyle {
        background-color: rgb(235, 239, 254);
        color: rgb(48, 91, 249);
      }
      .edocStyle {
        background-color: #fff4da;
        color: #ff9f00;
      }
      .signedOrsendStyle {
        color: #ef5350;
        background-color: rgba(239, 83, 80, 0.1);
      }
    }
  }
  .link-color {
    color: var(--theme-brand6, #1f85ec);
  }
  .danger-color {
    color: #fb3a36;
  }
</style>
